package scatter.wwd.rest.componentimpl.authority;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.area.rest.service.IAreaService;
import scatter.common.LoginUser;
import scatter.common.dict.PublicDictEnums;
import scatter.common.rest.monitor.MonitorTool;
import scatter.dict.pojo.po.Dict;
import scatter.dict.rest.service.IDictService;
import scatter.identifier.pojo.po.Identifier;
import scatter.identifier.rest.service.IIdentifierService;
import scatter.usersimple.pojo.po.UserSimple;
import scatter.usersimple.rest.service.IUserSimpleService;
import scatter.wwd.pojo.login.WwdAppLoginUser;
import scatter.wwd.pojo.po.UserInfo;
import scatter.wwd.rest.service.IUserInfoService;
import scatter.wxmp.pojo.login.WxMpLoginUser;
import scatter.wxmp.pojo.po.WxMpUser;
import scatter.wxmp.rest.security.WxMpUserDetailsServiceListener;

import java.util.Optional;

/**
 * 添加汪汪队用户信息
 * Created by yangwei
 * Created at 2021/1/8 13:29
 */
@Service
public class WxMpUserDetailsServiceListenerImpl implements WxMpUserDetailsServiceListener {

    @Autowired
    private IIdentifierService iIdentifierService;
    @Autowired
    private IUserSimpleService iUserSimpleService;
    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IDictService iDictService;
    @Autowired
    private IAreaService iAreaService;

    @Override
    public LoginUser onUserInfoReady(WxMpUser mpUser, String appId, WxMpLoginUser wxMpLoginUser) {
        Identifier byIdentifier = iIdentifierService.getByIdentifier(mpUser.getOpenId());

        boolean isNewUser = false;
        if (byIdentifier == null) {
            // 不存在添加
            byIdentifier = addByWxMpUser(mpUser);
            isNewUser = true;


        }
        UserSimple byId = iUserSimpleService.getById(byIdentifier.getUserId());
        //性别取用户信息字段
        UserInfo userInfo = iUserInfoService.getByUserId(byId.getId());
        if (userInfo!=null) {
            byId.setGenderDictId(userInfo.getGenderDictId());
        }
        Dict genderDict = iDictService.getById(byId.getGenderDictId());

        String gender = Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null);

        WwdAppLoginUser wwdAppLoginUser = new WwdAppLoginUser(); //LoginMapStruct.INSTANCE.map(wxMpLoginUser);
        wwdAppLoginUser.setUser(byId);
        wwdAppLoginUser.setUserIdentifier(byIdentifier);
        wwdAppLoginUser.addAuthority(wxMpLoginUser.getStringAuthorities());
        wwdAppLoginUser.addAuthority("appclient");
        // 将性别添加到当前登录用户
        wwdAppLoginUser.setGender(gender);
        wwdAppLoginUser.setGender(Optional.ofNullable(genderDict).map(Dict::getValue).orElse(null));

        if (isNewUser) {
            // 新用户注册监控
            MonitorTool.count("wwd.newuser.registry","汪汪队新用户注册",
                    "appCode", mpUser.getAppCode(),
                    "gender", Optional.ofNullable(genderDict).map(Dict::getValue).orElse("none"),
                    "city", Optional.ofNullable(mpUser.getCityName()).orElse("none")
            );
        }

        return wwdAppLoginUser;
    }

    /**
     * 添加用户信息
     * @param mpUser
     * @return
     */
    public Identifier addByWxMpUser(WxMpUser mpUser) {

        // 添加 wwd 用户信息
        UserSimple user = new UserSimple();
        user.setNickname(mpUser.getNickname());
        user.setGenderDictId(mpUser.getGenderDictId());
        user.setIsLock(false);
        user.setAvatar(mpUser.getAvatar());
        user.setGroupFlag(PublicDictEnums.UserGroupFlagDictItem.wx_mp.name());
        iUserSimpleService.save(user);

        // 添加用户登录标识信息
        Identifier userIdentifier = new Identifier();
        userIdentifier.setUserId(user.getId());
        userIdentifier.setIdentifier(mpUser.getOpenId());
        userIdentifier.setIdentityTypeDictId(iDictService.getIdByGroupCodeAndValue(Identifier.TypeDictGroup.account_type.groupCode(),Identifier.TypeDictItem.wx_mp.itemValue()));
        userIdentifier.setIsLock(false);
        userIdentifier.setIsExpired(false);
        userIdentifier.setIsDisabled(false);
        userIdentifier.setGroupFlag(PublicDictEnums.UserGroupFlagDictItem.wx_mp.name());
        iIdentifierService.save(userIdentifier);

        // 添加用户详细信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setGenderDictId(mpUser.getGenderDictId());
        userInfo.setNickname(mpUser.getNickname());
        userInfo.setName(mpUser.getNickname());
        userInfo.setPicUrl(StrUtil.nullToEmpty(mpUser.getAvatar()));
        userInfo.setIsHasCar(false);
        userInfo.setIsHasHourse(false);
        userInfo.setIsVerified(false);
        userInfo.setIsShowInList(false);
        iUserInfoService.save(userInfo);

        // 微信公众号登录不需要添加密码信息

        return userIdentifier;
    }
}
